import type { ZkbzAddEmits, ZkbzAddProps } from "../zkbz-add-dl/prop"
import { addZksjList, getZksj, getZkpDxList, MAGIC_SUCC_CODE } from "@api"
import { debounce, uuid } from "@ui/utils/win"
import type { SetupContext } from "vue"
import { zkspZdObj, zkbzZdObj } from "@utils/dic"
import { format, getMonthDays } from "@ui/utils/date"
export function use(props: ZkbzAddProps, emit: SetupContext<ZkbzAddEmits>['emit']) {
  const zkyf = ref(format(new Date(), 'yyyy/MM')),
    currentRow = ref(),
    tableData = ref<LisZkpBzItem[]>([]),
    formTable = ref(),
    queryT = debounce(query, 100)
  let zksj = {}
  watch(() => props.data, queryT, { immediate: true })
  watch(() => zkyf.value, queryT, { immediate: true })
  function query() {
    const { id, yqid, zkpid } = props.data, yf = zkyf.value
    if (id && yf) {
      zksj = {}
      const kssj = `${yf}/01 00:00:00`
      getZkpDxList({ xmid: id, yqid, zkpid }).then(({ data: { list } }) => {
        list.forEach(({ zbjg, zkbz }) => {
          zksj[zbjg] = zkbz
        })
        getZksj({ zbid: id, yqid, zkpid, kssj, jssj: `${yf}/${getMonthDays(new Date(kssj))} 23:59:59` }).then(({ data: { list } }) => {
          tableData.value = list.map(it => {
            it.zkspdm_mc = zkspZdObj[it.zkspdm]
            it.zk = judgeZk(it.cs1)
            it.zk_mc = zkbzZdObj[it.zk]
            return it
          })
        })
      })
    } else {
      tableData.value = []
    }
  }
  function setFormData(data: any) {
    tableData.value = data
    nextTick(() => {
      if (formTable.value) {
        formTable.value.layout()
      }
    })
  }
  function add() {
    const data = { ...props.data, id: uuid(), fs: 1 }
    tableData.value.push(data as LisZkpBzItem)
  }
  function del() {
    const obj = currentRow.value
    if (obj) {
      const { id } = obj
      setFormData(tableData.value.filter(it => it.id != id))
    } else {
      ElMessage({ type: 'warning', message: '请选择要删除的项目' })
    }
  }
  function save() {
    const { yqid, id, zkpid } = props.data
    addZksjList({ data: tableData.value, yqid, zbid: id, zkpid }).then(({ code, data, message }) => {
      if (code === MAGIC_SUCC_CODE) {
        ElMessage({ type: 'success', message: '保存成功' })
        query()
      } else
        ElMessage({ type: 'warning', message })
    })
  }
  function judgeZk(v: string) {
    return zksj[v] || '0'
  }
  function tableCellChange({ name, index, v }) {
    const data = tableData.value[index - 1]
    if (name === 'jlsj') {
      data.jlrq = v ? format(new Date(v)) : ''
    } else if (name === 'cs1') {
      data.zk = judgeZk(v)
      data.zk_mc = zkbzZdObj[data.zk]
    }
  }
  return { tableData, add, formTable, save, del, currentRow, query, zkyf, tableCellChange }
}